import 'dart:async';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/utils/log_util.dart';
import 'package:get/get.dart';

import '../../../bean/bean_integral.dart';
import '../../../bean/bean_train.dart';
import '../../../bean/bean_video.dart';
import '../../../bean/bean_video_course.dart';
import '../../../common/user_helper.dart';
import '../../../face/face_detector_view.dart';
import '../../../net/dio_utils.dart';
import '../../../utils/duration_utils.dart';
import '../../../utils/toast_utils.dart';
import '../course/video_progress_request_model.dart';

class VideoDetailsPPtController extends GetxController
    with VideoProgressRequestModel {
  VideoModel videoModel;
  int trainId;
  IntegralStatBean integralStatBean;
  TrainBean trainBean;
  int faceRecognitionNumber = 0;
  VideoDetailsPPtController(
    this.videoModel,
    this.integralStatBean,
    this.trainId,
    this.trainBean,
  );

  ///用户当前视频的学习进度
  UserStudyCourseBean userStudyCourseBean;
  bool loadingUserStudy = true;

  void initFunction() async {
    userStudyCourseBean =
        await getCurrentVideo(videoId: videoModel.id, trainId: trainId);
    loadingUserStudy = false;
    if (userStudyCourseBean != null) {
      _studyFinish = userStudyCourseBean.studyFinish;
      _currentTimers2 = userStudyCourseBean.studySecond;
      LogUtils.e("userStudyCourseBean is not null $_currentTimers2");
    } else {
      _currentTimers2 = 0;
      LogUtils.e("userStudyCourseBean is null ");
    }
    update(["progress"]);
    if (integralStatBean != null) {
      LogUtils.e("打开定时器 integralStatBean");
      startTimer();
    }
    if (_currentTimers2 < videoModel.videoSecond) {
      LogUtils.e("打开定时器 计算观看时间 $_currentTimers2");
      if (_studyFinish == 0) {
        startTimer2();
      }
    } else {
      LogUtils.e("未打开定时器 不计算观看时间 $_currentTimers2  ${videoModel.videoSecond}");
    }
  }

  Timer _timer;
  int _currentTimers = 0;

  ///[integralStatBean]不为null的时候才会调用
  void startTimer() {
    _currentTimers = 0;
    LogUtils.e(
        "打开定时器 当前视频 videoId is ${videoModel.id} 配置 configId IS ${integralStatBean.id}");
    _timer = Timer.periodic(Duration(seconds: 1), (Timer timer) {
      _currentTimers++;
      LogUtils.e("定时器 $_currentTimers ");
      if (_currentTimers == integralStatBean.readTimes) {
        stopTimer();
        LogUtils.e("添加积分 ");
        requestPlayRecoder(
            videoId: videoModel.id, configId: integralStatBean.id.toInt());
      }
    });
  }

  void stopTimer() {
    if (_timer != null && _timer.isActive) {
      _timer.cancel();
      _timer = null;
      LogUtils.e("关闭定时器 ");
    }
  }

  Timer _timer2;
  int _currentTimers2 = 0;

  ///0 学习未完成  1学习完成
  int _studyFinish = 0;

  String getVideoProgress() {
    return DurationUtils.fromatMil2(_currentTimers2);
  }

  String getVideoTotal() {
    return DurationUtils.fromatMil2(videoModel.videoSecond);
  }

  double getCurrentProgressValue() {
    if (videoModel.videoSecond <= 0) {
      return 0.0;
    }
    return _currentTimers2 * 1.0 / videoModel.videoSecond;
  }

  String getCurrentProgressStr() {
    if (videoModel.videoSecond <= 0) {
      return "0%";
    }
    num tag = _currentTimers2 * 1.0 / videoModel.videoSecond * 100;
    if (tag > 100) {
      tag = 100;
    }
    String str = "${tag.toStringAsFixed(0)}%";
    LogUtils.e(str);
    return str;
  }

  void startTimer2() {
    LogUtils.e("打开定时器 同步用户学习记录 当前视频 videoId is ${videoModel.id} ");
    _timer2 = Timer.periodic(Duration(seconds: 1), (Timer timer) async {
      _currentTimers2 += 1;
      faceRecognitionNumber += 1;
      UserHelper.getInstance.faceRecognitionNumber = faceRecognitionNumber;
      if (_currentTimers2 >= videoModel.videoSecond) {
        LogUtils.e("定时器 统计用户学习记录详情 取消计时");
        _timer2.cancel();
        _currentTimers2 = videoModel.videoSecond;
        LogUtils.e("定时器 统计用户学习记录详情 上报记录");
        await updateVideoProgress();
        LogUtils.e("定时器 统计用户学习记录详情 获取记录");
        userStudyCourseBean =
            await getCurrentVideo(videoId: videoModel.id, trainId: trainId);
        if (userStudyCourseBean != null) {
          _studyFinish = userStudyCourseBean.studyFinish;
          if (_studyFinish == 1) {
            ToastUtils.showToast("恭喜你，学习完成");
          }
        }
        update(["progress"]);
      } else {
        LogUtils.e(
            "定时器 统计用户学习记录详情 ppt $_currentTimers2  ${videoModel.videoSecond}");
        update(["progress"]);
        if (_currentTimers2 % 120 == 0) {
          LogUtils.e("定时器 统计用户学习记录详情 ---2分钟上报播放记录");
          updateVideoProgress();
        }
      }

      bool isShowFaceCheck = UserHelper.getInstance.isShowFaceCheck();
      if (!isShowFaceCheck) {
        debugPrint("人脸识别权限未打开");
        return;
      }

      ///-----------------ppt 培训人脸识别信息判断 ---------------------------------------------------------start ----------------------------------------------------------
      if (trainBean != null) {
        String faceRecognition = trainBean.faceRecognition;
        if (faceRecognition == "on") {
          //自动识别的间隔时间 分钟
          int faceRecognitionTime = trainBean.faceRecognitionTime;
          //分钟转秒
          int faceRecognitionTimeSeconds = faceRecognitionTime * 60;
          //测试使用
          // faceRecognitionTimeSeconds = 10;
          //如果本地时间大于人脸识别时间
          debugPrint(
            "人脸识别时间 faceRecognitionTimeSeconds：$faceRecognitionTimeSeconds  faceRecognitionNumber：${faceRecognitionNumber}",
          );

          if (faceRecognitionNumber > faceRecognitionTimeSeconds) {
            LogUtils.e("定时器 统计用户学习记录详情 ---人脸识别时间上报播放记录");
            updateVideoProgress();
            debugPrint("需要开启人脸识别 暂停计时");
            _timer2.cancel();
            _timer2 = null;
            dynamic result = await Get.defaultDialog(
                title: "提示",
                content: Text("本培训需要人脸识别认证"),
                textCancel: "取消",
                textConfirm: "去认证",
                radius: 10,
                onConfirm: () {
                  Get.back(result: true);
                });
            if (result == null || !result) {
              debugPrint("未选择去认证");
              ToastUtils.showToast("需要认证后才能继续学习");
              Get.back();
              return;
            }

            openFacePage();
          }
        }
      } else {
        debugPrint("trainBean is null 不识别人脸信息");
      }

      ///-----------------PPT 培训人脸识别信息判断 ---------------------------------------------------------end ----------------------------------------------------------
    });
  }

  Future<bool> openFacePage() async {
    dynamic faceResult = await Get.to(() => FaceDetectorView(
          key: UniqueKey(),
        ));
    if (faceResult == null || faceResult.toString().isEmpty) {
      ToastUtils.showToast("需要认证后才能继续学习");
      Get.back();
      return false;
    }
    //比对一下当前的人脸数据
    ResponseInfo statisRresponseInfo = await DioUtils.instance
        .postRequest(url: HttpHelper.compareFaceUrl, encrypt: false, jsonMap: {
      "videoId": videoModel.id,
      "trainId": trainId,
      "faceType": "train",
      "faceImageUrl": faceResult.toString(),
    });

    if (statisRresponseInfo.success) {
      //识别成功 继续播放
      debugPrint("人脸识别成功 继续播放");
      faceRecognitionNumber = 0;
      startTimer2();
    } else {
      dynamic result = await Get.defaultDialog(
          radius: 10,
          title: "人脸信息核定失败",
          content: Text(statisRresponseInfo.message ?? "网络请求错误"),
          textCancel: "关闭");
      Get.back();
      return true;
    }
    return false;
  }

  CancelToken _courseToken;

  Future<bool> updateVideoProgress() async {
    if (_courseToken != null && _courseToken.isCancelled) {
      _courseToken.cancel();
    }
    _courseToken = new CancelToken();
    Map<String, dynamic> jsonMap = {
      "videoId": videoModel.id,
      "trainId": trainId,
      "studySecond": _currentTimers2,
      "videoTypes": videoModel.videoTypes,
      "videoSecond": videoModel.videoSecond,
      "videoCourseId": videoModel.videoCourseId,
    };
    ResponseInfo statisRresponseInfo = await DioUtils.instance.postRequest(
        url: HttpHelper.videoStudyProgressUpdateUrl,
        cancelTag: _courseToken,
        encrypt: true,
        jsonMap: jsonMap);
    if (statisRresponseInfo.success) {
      return true;
    }
    return false;
  }

  void stopTimer2() {
    if (_timer2 != null && _timer2.isActive) {
      _timer2.cancel();
      _timer2 = null;
      LogUtils.e("关闭定时器 ");
    }
  }

  @override
  void onClose() {
    this.stopTimer2();
    this.stopTimer();
    super.onClose();
  }

  void stopAllFunction() {
    LogUtils.e("应用进入后台 停止所有的功能 ");
    this.stopTimer2();
    this.stopTimer();
  }

  bool closeLoading = false;
  void closePage() async {
    if (closeLoading) {
      return;
    }
    closeLoading = true;
    update(['root']);
    //模拟拦截退出
    //await Future.delayed(Duration(seconds: 1));
    if (_studyFinish == 0) {
      await updateVideoProgress();
    }
    this.stopAllFunction();
    //获取当前正在播放的视频
    Get.back(result: true);
  }
}
